<template>
  <div id="main" style="width: 80vw;height:600px;"></div>
</template>
<script>
import * as echarts from "echarts";
import { COLORLIST } from "@/utils/variate";
import _ from "loadsh";
export default {
  props: {
    // 线形图数据
    lineData: {
      type: Object,
      required: true,
    },
    // 添加截取组
    moveingMark: {
      type: Array,
      default: () => [],
    },
    // 线移动数据
    moveLineList: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    moveLineList: {
      handler(value) {
        // 首次进去赋值缓存，
        if (!this.oldMoveLineList.length) {
          this.oldMoveLineList = _.cloneDeep(value);
          return;
        }
        // 每次操作的差异是多少
        let differenceNum = 0;
        // 对比新旧数据差异，找到此次操作的那个孔号，减少循环，避免多次渲染
        const differenceItem = value.find((item, index) => {
          let currentDiffItem = item.num !== this.oldMoveLineList[index]?.num;
          if (currentDiffItem) {
            // 判断操作的孔号，是加还是减
            differenceNum = item.num - this.oldMoveLineList[index]?.num;
          }
          return currentDiffItem;
        });
        if (!differenceItem) return;
        this.$nextTick(() => {
          setTimeout(() => {
            // 获取图形的配置项
            const serviceOptions = this.myChart?.getOption()?.series;
            // 动态添加配置
            this.myChart.setOption({
              series: [
                ...serviceOptions,
                serviceOptions.find((item) => {
                  if (item.name === differenceItem.name) {
                    for (let i = 0; i < item.data.length; i++) {
                      item.data[i][0] -= differenceNum;
                    }
                    // this.myChart.resize()
                  }
                }),
              ],
            });
            this.oldMoveLineList = _.cloneDeep(value);
          }, 200);
        });
      },
      deep: true,
    },
    lineData: {
      handler(value) {
        this.$nextTick(() => {
          this.setLinsttypeData(value);
        });
      },
      deep: true,
      immediate: true,
    },
    moveingMark: {
      handler(value) {
        this.moveingMarkLines = value;
        this.$emit('handleChange', this.moveingMarkLines)
        // 获取图形的配置项
        const serviceOptions = this.myChart?.getOption()?.series;
        // 动态添加配置
        this.myChart.setOption({
          series: serviceOptions.map((item, index) => {
            if (index === 0) {
              return {
                ...item,
                type: "line",
                markArea: {
                  data: this.group(this.moveingMarkLines, 2).map((item) => {
                    return item.map((i) => {
                      return {
                        xAxis: i.x,
                        name: i.id,
                        label: {
                          color: i.backgroundColor,
                        },
                        itemStyle: {
                          color: i.backgroundColor,
                        },
                      };
                    });
                  }),
                },
                markLine: {
                  symbol: "none",
                  animation: false,
                  data: this.moveingMarkLines.map((item) => {
                    return {
                      name: item.id,
                      xAxis: item.x,
                      lineStyle: {
                        type: "dashed",
                        width: 3,
                        color: item.color,
                      },
                      label: {
                        color: item.color,
                        show: true,
                        fontSize: 16,
                        fontWeight: "bolder",
                      },
                    };
                  }),
                },
              };
            } else {
              return item
            }
          }),
        });
        // this.initChart();
      },
      deep: true,
    },
  },
  data() {
    return {
      myChart: null,
      originData: [], // 图形数据
      moveingMarkLines: [],
      oldMoveLineList: [],
      // [
      //   {
      //     id: "L1",
      //     x: 50,
      //     backgroundColor: "rgba(0, 193, 255, 0.2)",
      //     color: "#00b0f0",
      //   },
      //   {
      //     id: "L2",
      //     x: 100,
      //     backgroundColor: "rgba(0, 193, 255, 0.2)",
      //     color: "#00b0f0",
      //   },
      //   {
      //     id: "L3",
      //     x: 200,
      //     backgroundColor: "rgba(9, 128, 23, 0.2)",
      //     color: "#098017",
      //   },
      //   {
      //     id: "L4",
      //     x: 300,
      //     backgroundColor: "rgba(9, 128, 23, 0.2)",
      //     color: "#098017",
      //   },
      // ],
    };
  },
  mounted() {
    this.initChart();
  },
  methods: {
    setLinsttypeData(lines) {
      const maxValue = Math.max(
        ...Object.values(lines).map((item) => item.length)
      );
      let xAxisList = Array.from({ length: maxValue }, (_, i) => i);
      let result = {};
      for (const k in lines) {
        result[k] = xAxisList.map((item, index) => {
          return [item, lines[k][index]];
        });
      }
      this.originData = result;
      this.initChart();
    },
    initChart() {
      const chartDom = document.getElementById("main");
      this.myChart = echarts.init(chartDom);
      let option;

      option = {
        title: {
          text: "操作图形",
          color: "black",
          fontWeight: 600,
          fontSize: 18,
        },
        color: COLORLIST,
        legend: {
          type: "scroll",
          orient: "vertical",
          align: "left",
          right: "20",
          top: "60",
          icon: "circle",
          width: "80%",
          textStyle: {
            fontSize: 20,
          },
        },
        grid: {
          left: "3%",
          right: "13%",
          containLabel: true,
          bottom: 0,
        },
        tooltip: {
          // trigger: 'axis',
          axisPointer: {
            type: "cross",
          },
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          id: "x0",
          type: "value",
          // boundaryGap: false,
          // inverse: true,
          minorTick: {
            show: true,
          },
          axisLine: {
            onZero: false,
          },
          axisTick: {
            show: true,
            inside: true,
          },
          axisLabel: {
            formatter: "{value}",
            textStyle: {
              fontWeight: 700,
              color: "#4c4c4c",
              fontSize: 20,
            },
          },
          splitLine: {
            show: false,
          },
        },
        yAxis: {
          id: "y0",
          type: "value",
          splitNumber: 4,
          minorTick: {
            show: true,
          },
          axisTick: {
            show: true,
            inside: true,
          },
          axisLine: {
            onZero: false,
            show: true,
            lineStyle: {
              color: "black",
            },
          },
          axisLabel: {
            formatter: "{value}",
            textStyle: {
              fontWeight: 700,
              color: "#4c4c4c",
              fontSize: 20,
            },
          },
          splitLine: {
            show: false,
          },
        },
        dataZoom: {
          type: "inside",
          zoomOnMouseWheel: "ctrl",
        },
        // visualMap: {
        //   show: false,
        //   dimension: 0,
        //   pieces: [
        //     {
        //       lte: 6,
        //       color: 'green'
        //     },
        //     {
        //       gt: 6,
        //       lte: 8,
        //       color: 'red'
        //     },
        //     {
        //       gt: 8,
        //       lte: 14,
        //       color: 'green'
        //     },
        //     {
        //       gt: 14,
        //       lte: 17,
        //       color: 'red'
        //     },
        //     {
        //       gt: 17,
        //       color: 'green'
        //     }
        //   ]
        // },
        servies: [],
      };
      const _this = this;
      setTimeout(() => {
        const imgItem = this.myChart.getConnectedDataURL({
          pixelRatio: 2, // 放大二倍下载
          backgroundColor: "#fff",
        });
        _this.$emit("shotImg", imgItem);
      }, 100);

      let serviceData = [];
      for (const k in this.originData) {
        serviceData.push({
          name: k,
          type: "line",
          smooth: true,
          symbol: "none",
          data: this.originData[k],
          lineStyle: {
            width: 3,
          },
        });
      }
      option.series = serviceData;
      // option.series[0] = {
      //   ...option.series[0],
      //   type: 'line',
      //   markArea: {
      //     data: this.group(this.moveingMarkLines, 2).map((item) => {
      //       return item.map((i) => {
      //         return {
      //           xAxis: i.x,
      //           name: i.id,
      //           label: {
      //             color: i.backgroundColor
      //           },
      //           itemStyle: {
      //             color: i.backgroundColor,
      //           },
      //         };
      //       });
      //     }),
      //   },
      //   markLine: {
      //     symbol: "none",
      //     animation: false,
      //     data: this.moveingMarkLines.map((item) => {
      //       return {
      //         name: item.id,
      //         xAxis: item.x,
      //         lineStyle: {
      //           type: "dashed",
      //           width: 3,
      //           color: item.color,
      //         },
      //         label: {
      //           color: item.color,
      //           show: true,
      //           fontSize: 16,
      //           fontWeight: "bolder",
      //         },
      //       };
      //     }),
      //   }
      // }
      // this.myChart.setOption({
      //   series: [ serviceData[0] ]
      // })

      let isClick = false;
      let currentId = null;
      this.myChart.on("mousedown", function(params) {
        if (params.componentType === "markLine") {
          // console.log('点击了', params.name)
          currentId = params.name;
          isClick = true;
        }
      });
      // this.myChart.getZr().on('mousemove', (params) => {
      //   if (isClick) {
      //   }
      // })
      this.myChart.getZr().on("mouseup", (params) => {
        if (!isClick) return;
        const pointInGrid = this.myChart.convertFromPixel("grid", [
          params.offsetX,
          params.offsetY,
        ]);
        const currentItem = this.moveingMarkLines.find(
          (item) => item.id === currentId
        );
        currentItem.x = pointInGrid[0];

        const currentService = this.myChart?.getOption()?.series?.[0];
        const markLineList = currentService?.markLine?.data;

        setTimeout(() => {
          this.myChart.setOption({
            series: [
              {
                markArea: {
                  data: this.group(this.moveingMarkLines, 2).map((item) => {
                    return item.map((i) => {
                      if (i.id === currentId) {
                        return {
                          xAxis: currentItem.x,
                          name: i.id,
                          label: {
                            color: i.backgroundColor,
                          },
                          itemStyle: {
                            color: i.backgroundColor,
                          },
                        };
                      } else {
                        return {
                          xAxis: i.x,
                          name: i.id,
                          label: {
                            color: i.backgroundColor,
                          },
                          itemStyle: {
                            color: i.backgroundColor,
                          },
                        };
                      }
                    });
                  }),
                },
                markLine: {
                  data: markLineList.map((item) => {
                    if (item.name === currentId) {
                      return {
                        ...item,
                        xAxis: currentItem.x,
                        // name: currentId,
                        // lineStyle: {
                        //   type: "dashed",
                        //   width: 3,
                        //   color: '#000'
                        // }
                      };
                    } else {
                      return { ...item };
                    }
                  }),
                },
              },
            ],
          });
        }, 500);
        isClick = false;
        this.$emit("handleChange", this.moveingMarkLines);
        // this.myChart.resize()
      });
      option && this.myChart.setOption(option, true);
    },
    group(array, subGroupLength) {
      let index = 0;
      let newArray = [];
      while (index < array.length) {
        newArray.push(array.slice(index, (index += subGroupLength)));
      }
      return newArray;
    },
  },
};
</script>
